<template>
	<view class="content">
		<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">登录授权</button>
	</view>
</template>

<script>
	import WXBizDataCrypt from '../static/js/wxdecode/WXBizDataCrypt.js'
	export default {
		data() {
			return {
				appId: this.config.appId,
				sessionKey: "",
				openId: ""
			}
		},
		onLoad() {
			this.login()
		},
		methods: {
			// 登录
			login(e) {
				uni.login({
					success: (res) => {
						console.log("login", res);
						if (res.errMsg == "login:ok") {
							var code = res.code
							var AppSecret = this.config.appSecret
							var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
								this.appId + "&secret=" + AppSecret + "&js_code=" +
								code + "&grant_type=authorization_code"
							uni.request({
								url: url,
								success: (res) => {
									console.log(res)
									if (res.errMsg == "request:ok") {
										this.sessionKey = res.data.session_key
										this.openId = res.data.openid
									}
								}
							})
						}
					}
				})
			},
			// 获取手机号
			getPhoneNumber(e) {
				if (this.sessionKey == "") {
					uni.showModal({
						title: "获取登录信息失败！"
					})
					return
				}
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					var appId = this.appId
					var sessionKey = this.sessionKey
					var encryptedData = e.detail.encryptedData
					var iv = e.detail.iv
					var pc = new WXBizDataCrypt(appId, sessionKey)
					var data = pc.decryptData(encryptedData, iv)
					console.log('解密后 data: ', data)
					/* uni.showModal({
						title: "手机号码",
						content: data.phoneNumber
					}) */
					this.appLoginWx(data.phoneNumber)
				}
			},
			appLoginWx(phoneNumber) {
				// #ifdef MP-WEIXIN
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: (res2) => {

									uni.getUserInfo({
										provider: 'weixin',
										success: (info) => { //这里请求接口
											info.userInfo.phoneNumber = phoneNumber
											console.log(info.userInfo);
											uni.setStorageSync('user', info.userInfo)
											uni.redirectTo({
												url: 'index'
											});
										},
										fail: () => {
											uni.showToast({
												title: "微信登录授权失败",
												icon: "none"
											});
										}
									})

								},
								fail: () => {
									uni.showToast({
										title: "微信登录授权失败",
										icon: "none"
									});
								}
							})

						} else {
							uni.showToast({
								title: '请先安装微信或升级版本',
								icon: "none"
							});
						}
					}
				});
				//#endif
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin: 500rpx auto;
	}
</style>
